package com.rdc.soulmatemusicplayer.base;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rdc.soulmatemusicplayer.R;
import com.rdc.soulmatemusicplayer.adapter.MusicListAdapter;
import com.rdc.soulmatemusicplayer.application.App;
import com.rdc.soulmatemusicplayer.bean.Song;
import com.rdc.soulmatemusicplayer.service.PlayService;
import com.rdc.soulmatemusicplayer.util.MusicUtils;

import java.util.ArrayList;
import java.util.List;


/**
* @file 本地音乐的Fragment
* @author Soul Mate
* @brief 本地音乐相关
*/
public class LocalFragment extends Fragment implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {


	private ListView mMusicListView;
	//	private ImageView mMusicIcon;
	private TextView mMusicTitle;
	private TextView mMusicArtist;

	private ImageView mPreImageView;
	private ImageView mPlayImageView;
	private ImageView mNextImageView;

	private SeekBar mMusicProgress;
	private TextView mPlayTime;
	private Thread mThread;

	private MusicListAdapter mMusicListAdapter;

	private MainActivity mActivity;

	//暂停
	private boolean isPause;
	private boolean isChanging;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//开启SeekBar与播放同步进度的线程
		mThread = new Thread(new SeekBarThread());
		mThread.start();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.local_music_fragment, container, false);

		//初始化歌单和
		setupViews(view);

		return view;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		//获取MainActivity
		mActivity = (MainActivity) activity;

	}


	/**
	 * view创建完毕 回调通知activity绑定歌曲播放服务
	 */
	@Override
	public void onStart() {
		super.onStart();

		//绑定服务
		mActivity.allowBindService();

	}

	@Override
	public void onResume() {
		super.onResume();
		isPause = false;
	}




	@Override
	public void onPause() {
		isPause = true;
		super.onPause();
	}

	/**
	 * 销毁，回调通知activity解除绑定歌曲播放服务
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		mActivity.allowUnbindService();
	}


	private void setupViews(View layout) {
		mMusicListView = (ListView) layout.findViewById(R.id.lv_music_list);
		List<Song> list = new ArrayList<Song>();
		//把扫描到的音乐赋值给list
		list = MusicUtils.getMusicData();
		mMusicListAdapter = new MusicListAdapter(App.sContext, list);
		mMusicListView.setAdapter(mMusicListAdapter);

		//获取控件
		mMusicListView = (ListView) layout.findViewById(R.id.lv_music_list);
//		mMusicIcon = (ImageView) layout.findViewById(R.id.iv_play_icon);
		mMusicTitle = (TextView) layout.findViewById(R.id.tv_play_title);
		mMusicArtist = (TextView) layout.findViewById(R.id.tv_play_artist);

		mPreImageView = (ImageView) layout.findViewById(R.id.iv_pre);
		mPlayImageView = (ImageView) layout.findViewById(R.id.iv_play);
		mNextImageView = (ImageView) layout.findViewById(R.id.iv_next);

		mPlayTime = (TextView) layout.findViewById(R.id.tv_play_time);
		mMusicProgress = (SeekBar) layout.findViewById(R.id.play_progress);


		mMusicListView.setOnItemClickListener(mMusicItemClickListener);

		//监控点击事件
		//		mMusicIcon.setOnClickListener(this);
		mPreImageView.setOnClickListener(this);
		mPlayImageView.setOnClickListener(this);
		mNextImageView.setOnClickListener(this);
		mMusicProgress.setOnSeekBarChangeListener(this);
	}

	//监控子项点击事件
	private AdapterView.OnItemClickListener mMusicItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			//播放
			play(position);
		}
	};

	/**
	 *
	 * @param position
	 */
	private void onItemPlay(int position)
	{
		// 若正在播放的歌曲没有显示，ListView自动滑动列表到播放的歌曲的位置
		mMusicListView.smoothScrollToPosition(position);

		// 设置新的播放位置
		mMusicListAdapter.setPlayingPosition(position);

	}

	/**
	 * 播放音乐item
	 *
	 * @param position
	 */
	private void play(int position) {
		int pos = mActivity.getPlayService().play(position);

		//更新数据
		onPlay(pos);
	}

	/**
	 * 播放时，更新控制面板
	 *
	 * @param position
	 */
	public void onPlay(int position) {
		if (MusicUtils.sMusicList.isEmpty() || position < 0) {
			Toast.makeText(getActivity(), "当前手机没有MP3文件", Toast.LENGTH_LONG).show();
			return;
		}
		//设置进度条的总长度
		mMusicProgress.setMax(mActivity.getPlayService().getDuration());

		//自动寻找歌曲位置
		onItemPlay(position);

		//Song music = MusicUtils.sMusicList.get(position);
		//		Bitmap icon = MusicIconLoader.getInstance().load(music.getImage());
		//		mMusicIcon.setImageBitmap(icon == null ? ImageTools
		//				.scaleBitmap(R.drawable.ic_launcher) : ImageTools
		//				.scaleBitmap(icon));

		//设置底部数据
		setData(position);

		//播放和暂停按钮的切换
		if (mActivity.getPlayService().isPlaying()) {
			mPlayImageView.setImageResource(android.R.drawable.ic_media_pause);
		} else {
			mPlayImageView.setImageResource(android.R.drawable.ic_media_play);
		}


	}

	//	设置底部播放栏TextView数据
	public void setData(int position) {

		mMusicTitle.setText(MusicUtils.sMusicList.get(position).title);
		mMusicArtist.setText(MusicUtils.sMusicList.get(position).artist);
	}

	//重写底部点击事件
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_play:
			if (mActivity.getPlayService().isPlaying())
			{
				mActivity.getPlayService().pause(); // 暂停
				mPlayImageView
						.setImageResource(android.R.drawable.ic_media_play);
			} else
				{
				onPlay(mActivity.getPlayService().resume()); // 播放，更新
				}
			break;
		case R.id.iv_next:
			mActivity.getPlayService().next(); // 下一曲
			onPlay(mActivity.getPlayService().getPlayingPosition());
			break;
		case R.id.iv_pre:
			mActivity.getPlayService().pre(); // 上一曲
			onPlay(mActivity.getPlayService().getPlayingPosition());
			break;
		}
	}



	/**
	 * SeekBar的操作
	 *
	 */

	//进度条改变后的操作
	@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
	{
		mPlayTime.setText(ShowTime(seekBar.getProgress()));
	}

	//开始触摸
	@Override public void onStartTrackingTouch(SeekBar seekBar)
	{
		//		isChanging = true;
	}

	//结束触摸
	@Override public void onStopTrackingTouch(SeekBar seekBar)
	{

		mActivity.getPlayService().SynchronousProgress(seekBar.getProgress());
		isChanging = false;

	}
	//	public Handler handler = new Handler(new Handler.Callback() {
	//
	//		@Override
	//		public boolean handleMessage(Message msg) {
	//			if (msg.what == 0x01) {
	//				mPlayTime.setText("00:00");
	////				mPlayTime.setText(LocalMusicUtils.formatTime(musicService.getCurrent()));
	//				mPlayTime.setText(ShowTime(mActivity.getPlayService().getmPlayer().getCurrentPosition()));
	//
	//				mMusicProgress.setProgress(mActivity.getPlayService().getmPlayer().getCurrentPosition());
	//				mMusicProgress.setMax(mActivity.getPlayService().getDuration());
	////				tvTotalTime.setText(LocalMusicUtils.formatTime(musicService.getTime()));
	////				mActivity.getPlayService().SynchronousProgress(mMusicProgress.getProgress());
	//
	////				seekBar.setMax(musicService.getTime());
	//				mMusicProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
	//					@Override
	//					public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
	////                        musicService.seekTo(progress);//出现重音
	////						mPlayTime.setText(ShowTime(mMusicProgress.getProgress()));
	//						mPlayTime.setText(ShowTime(mMusicProgress.getProgress()));
	//
	//					}
	//
	//					@Override
	//					public void onStartTrackingTouch(SeekBar seekBar) {
	//
	//					}
	//
	//					@Override
	//					public void onStopTrackingTouch(SeekBar seekBar) {
	//
	//						mActivity.getPlayService().SynchronousProgress(mMusicProgress.getProgress());
	////						isSeekBarChanging = false;
	////						musicService.seekTo(seekBar.getProgress());
	//						System.out.println(seekBar.getProgress());
	//					}
	//				});
	////				handler.sendEmptyMessage(0x01);
	//
	//			}
	//			return false;
	//		}
	//	});
	//	public class SeekBarThread implements Runnable{
	//
	//		@Override
	//		public void run() {
	//
	//			while(true){
	//				System.out.println("2222222222222222222222222222222");
	//				Message message = new Message();
	//				message.what = 0x01;
	////                message.obj = MusicService.mediaPlayer.getCurrentPosition();
	//
	//				handler.sendMessage(message);
	//
	//				try{
	//					Thread.sleep(10);
	//				}catch (Exception e){
	//					e.printStackTrace();
	//				}
	//			}
	//		}
	//	}
	//

	//播放进度时间的转换
	public String ShowTime(int time)
	{
		time/=1000;
		int minute = time/60;
		int second = time%60;
		minute%=60;
		return String.format("%02d:%02d",minute,second);
	}


	//	自定义更新SeekBar的线程
	class SeekBarThread implements  Runnable
	{

		@Override public void run()
		{
			while(true )

			{
				if(mActivity.mPlayService != null)
				{
					mMusicProgress.setProgress(mActivity.mPlayService.getCurrent());
				}

				try
				{
					Thread.sleep(100);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}

			}
		}
	}
	
}


